package com.zhike.service.collect.impl;

import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zhike.common.repository.Collect;
import com.zhike.common.vo.UserInfo4Cache;
import com.zhike.service.collect.ICollectRepository;
import com.zhike.utils.cache.UsersInfoCacheProvider;

import lombok.extern.slf4j.Slf4j;

@Repository
@Slf4j
public class CollectServiceRepository implements ICollectRepository {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private UsersInfoCacheProvider usersInfoCacheProvider;

    @Override
    public Boolean saveCollect(Collect collect) {
        Collect hm = mongoTemplate.insert(collect);
        log.debug("save collect succ {}", hm);
        return hm != null;
    }

    @Override
    public Boolean deleteCollect(String[] ids) {
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").in(ids));
        return mongoTemplate.remove(query, Collect.class).getDeletedCount() > 0;
    }

    @Override
    public List<Collect> findCollects(String uid, String collectType) {
        Query query = new Query();
        query.addCriteria(Criteria.where("uid").is(uid));
        if (StringUtils.isNotBlank(collectType)) {
            query.addCriteria(Criteria.where("cType").is(collectType));
        }

        List<Collect> list = mongoTemplate.find(query, Collect.class);
        for (Collect c : list) {
            UserInfo4Cache uc = usersInfoCacheProvider.get(c.getUid());
            c.setSenderNickname(uc.getNickName());
        }
        return list;
    }

    @Override
    public Collect findAndModify(String messageId, String userId) {
        Update update = new Update()
                .set("timestamp", new Date());
        Query query = new Query(
                Criteria.where("messageId").is(messageId)
                        .and("userId").is(userId));
        return mongoTemplate.findAndModify(query, update, Collect.class);
    }
}
